﻿using ASP;
using ClassLibrary.BusinessLayer.Facade;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using SysOperationLayer.DBHandle;
using SysComm;

public partial class AgentsUpdate : Page, IRequiresSessionState
{
    LogDB m_logdb = new LogDB();
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.clearText();
        this.setTextReadOnly(false);
        this.setButtons(string.Empty);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Agents");
        if (!canDelete.CanDelete())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoDelete.ToString();
        }
        else
        {
            try
            {
                string trueUpdateStr = string.Empty;
                string falseUpdateStr = string.Empty;
                if (Session["Culture"] != null)
                {

                    if (Session["Culture"].ToString() == "zh-TW")
                    {
                        trueUpdateStr = "刪除成功!";
                        falseUpdateStr = "刪除失敗!";

                    }
                    else if (Session["Culture"].ToString() == "zh-CN")
                    {
                        trueUpdateStr = "删除成功!";
                        falseUpdateStr = "删除失败!";
                    }
                    else
                    {
                        trueUpdateStr = "Delete succeed!";
                        falseUpdateStr = "Delete failed!";
                    }
                }

                this.ODSAgent.DeleteMethod = "Delete";
                this.ODSAgent.DeleteParameters["IsDelete"].DefaultValue = "true";
                this.ODSAgent.DeleteParameters["DeleteBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSAgent.DeleteParameters["DeleteIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                this.ODSAgent.DeleteParameters["Original_Agent"].DefaultValue = this.txtAgent.Text;

                if (this.ODSAgent.Delete() < 0)
                {
                    IPMS.Common.Jscript.AlertAndRedirect(trueUpdateStr, "OptAgents.aspx", this.Page);
                    m_logdb.writeSucLog(SysUtil.m_functiong_agent, "delete agent succeed!");
                }
                else
                {
                    IPMS.Common.Jscript.Alert(falseUpdateStr, this.Page);
                    m_logdb.writeFaileLog(SysUtil.m_functiong_agent, "delete agent faile!");
                }
                this.clearText();
                this.setTextReadOnly(false);
                this.setButtons(string.Empty);
            }
            catch (Exception ex)
            {
                List<string> lstValues = new List<string>();
                // this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
                this.lblError.Text = ex.Message.ToString();
                this.chkForOperation.Checked = true;
            }
        }
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Agents");
        if (!canDelete.CanUpdate())
        {
             this.lblError.Visible = true;
             this.lblError.Text = Messages.mNoEdit.ToString();
        }
        else
        {
            this.setTextReadOnly(false);
            this.setButtons("modify");
            this.txtAgent.ReadOnly = true;
            this.txtName.Focus();
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Agents");
        if (!canDelete.CanAdd())
        {
             this.lblError.Visible = true;
             this.lblError.Text = Messages.mNoAdd.ToString();
        }
        else
        {
            this.setTextReadOnly(false);
            this.clearText();
            this.setButtons("new");
            this.txtAgent.ReadOnly = false;
            this.txtAgent.Focus();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string trueUpdateStr = string.Empty;
            string falseUpdateStr = string.Empty;
            string trueInsertStr = string.Empty;
            string falseInsertStr = string.Empty;
            if (Session["Culture"] != null)
            {

                if (Session["Culture"].ToString() == "zh-TW")
                {
                    trueUpdateStr = "更新成功!";
                    falseUpdateStr = "更新失败!";
                    trueInsertStr = "添加成功!";
                    falseInsertStr = "添加失敗!";
                }
                else if (Session["Culture"].ToString() == "zh-CN")
                {
                    trueUpdateStr = "更新成功!";
                    falseUpdateStr = "更新失败!";
                    trueInsertStr = "添加成功!";
                    falseInsertStr = "添加失败!";
                }
                else
                {
                    trueUpdateStr = "Update succeed!";
                    falseUpdateStr = "Update failed!";
                    trueInsertStr = "Add succeed!";
                    falseUpdateStr = "Add failed!";
                }
            }

            if (this.cbForUpdate.Checked)
            {
                this.ODSAgent.UpdateMethod = "Update";
                this.ODSAgent.UpdateParameters["Name"].DefaultValue = this.txtName.Text;
                this.ODSAgent.UpdateParameters["ChineseName"].DefaultValue = this.txtChiName.Text;
                this.ODSAgent.UpdateParameters["Address"].DefaultValue = this.txtAddress.Text;
                this.ODSAgent.UpdateParameters["ContactPerson"].DefaultValue = this.txtContactPerson.Text;
                this.ODSAgent.UpdateParameters["JobTitle"].DefaultValue = this.txtJobTitle.Text;
                this.ODSAgent.UpdateParameters["Phone"].DefaultValue = this.txtPhone.Text;
                this.ODSAgent.UpdateParameters["Fax"].DefaultValue = this.txtFax.Text;
                this.ODSAgent.UpdateParameters["Phone2"].DefaultValue = this.txtPhone2.Text;
                this.ODSAgent.UpdateParameters["WebSite"].DefaultValue = this.txtWebSite.Text;
                this.ODSAgent.UpdateParameters["ContactPerson2"].DefaultValue = this.txtContactPerson2.Text;
                this.ODSAgent.UpdateParameters["Fax2"].DefaultValue = this.txtFax2.Text;
                this.ODSAgent.UpdateParameters["EmailAddress"].DefaultValue = this.txtEmailAddress.Text;
                this.ODSAgent.UpdateParameters["EmailAddress2"].DefaultValue = this.txtEmailAddress2.Text;
                this.ODSAgent.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSAgent.UpdateParameters["Original_Agent"].DefaultValue = this.txtAgent.Text;
                this.ODSAgent.UpdateParameters["UpdateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;

                if (this.ODSAgent.Update() < 0)
                {
                    IPMS.Common.Jscript.AlertAndRedirect(trueUpdateStr, "OptAgents.aspx", this.Page);
                    m_logdb.writeSucLog(SysUtil.m_functiong_agent, "update agent succeed!");
                }
                else
                {
                    IPMS.Common.Jscript.Alert(falseUpdateStr, this.Page);
                    m_logdb.writeFaileLog(SysUtil.m_functiong_agent, "update agent faile!");
                }
            }
            else
            {
                this.ODSAgent.InsertMethod = "Insert";
                this.ODSAgent.InsertParameters["Agent"].DefaultValue = this.txtAgent.Text;
                this.ODSAgent.InsertParameters["Name"].DefaultValue = this.txtName.Text;
                this.ODSAgent.InsertParameters["ChineseName"].DefaultValue = this.txtChiName.Text.ToString();
                this.ODSAgent.InsertParameters["Address"].DefaultValue = this.txtAddress.Text;
                this.ODSAgent.InsertParameters["ContactPerson"].DefaultValue = this.txtContactPerson.Text;
                this.ODSAgent.InsertParameters["JobTitle"].DefaultValue = this.txtJobTitle.Text;
                this.ODSAgent.InsertParameters["Phone"].DefaultValue = this.txtPhone.Text;
                this.ODSAgent.InsertParameters["Fax"].DefaultValue = this.txtFax.Text;
                this.ODSAgent.InsertParameters["Phone2"].DefaultValue = this.txtPhone2.Text;
                this.ODSAgent.InsertParameters["WebSite"].DefaultValue = this.txtWebSite.Text;
                this.ODSAgent.InsertParameters["ContactPerson2"].DefaultValue = this.txtContactPerson2.Text;
                this.ODSAgent.InsertParameters["Fax2"].DefaultValue = this.txtFax2.Text;
                this.ODSAgent.InsertParameters["EmailAddress"].DefaultValue = this.txtEmailAddress.Text;
                this.ODSAgent.InsertParameters["EmailAddress2"].DefaultValue = this.txtEmailAddress2.Text;
                this.ODSAgent.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSAgent.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSAgent.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupID"].ToString();
                this.ODSAgent.InsertParameters["CreateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;

                if (this.ODSAgent.Insert() < 0)
                {
                    IPMS.Common.Jscript.AlertAndRedirect(trueInsertStr, "OptAgents.aspx", this.Page);
                    m_logdb.writeSucLog(SysUtil.m_functiong_agent, "add agent succeed!");
                }
                else
                {
                    IPMS.Common.Jscript.Alert(falseInsertStr, this.Page);
                    m_logdb.writeFaileLog(SysUtil.m_functiong_agent, "add agent faile!");
                }
            }
            this.setTextReadOnly(false);
            this.setButtons("save");
            this.cbForUpdate.Checked = false;
            this.clearText();
            // this.Search();
        }
        catch (Exception ex)
        {
            List<string> lstValues = new List<string>();
            //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
            this.lblError.Text = ex.Message.ToString();
            this.chkForOperation.Checked = true;
        }
    }

    //protected void btnSearch_Click(object sender, EventArgs e)
    //{
    //    this.Search();
    //}

    protected void clearText()
    {
        this.txtAgent.Text = string.Empty;
        this.txtName.Text = string.Empty;
        this.txtChiName.Text = string.Empty;
        this.txtContactPerson.Text = string.Empty;
        this.txtAddress.Text = string.Empty;
        this.txtJobTitle.Text = string.Empty;
        this.txtPhone.Text = string.Empty;
        this.txtFax.Text = string.Empty;
        this.txtPhone2.Text = string.Empty;
        this.txtContactPerson2.Text = string.Empty;
        this.txtFax2.Text = string.Empty;
        this.txtWebSite.Text = string.Empty;
        this.txtEmailAddress.Text = string.Empty;
        this.txtEmailAddress2.Text = string.Empty;
        this.cbForUpdate.Checked = false;
        this.chkForOperation.Checked = false;
        this.lblError.Text = "";
    }

    //protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    //{
    //    this.GridView1.PageIndex = e.NewPageIndex;
    //    this.GridView1.DataBind();
    //    this.Search();
    //}

    //protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        this.chkForOperation.Checked = true;
    //        this.cbForUpdate.Checked = true;
    //        Agent runMethod = new Agent(this.GridView1.DataKeys[this.GridView1.SelectedIndex].Values["Agent"].ToString());
    //        runMethod.GetAgentDetails();
    //        this.txtAgent.Text = runMethod.Agent_Code;
    //        this.txtName.Text = runMethod.Agent_Name;
    //        this.txtChiName.Text = runMethod.Agent_ChineseName;
    //        this.txtContactPerson.Text = runMethod.Agent_ContactPerson;
    //        this.txtAddress.Text = runMethod.Agent_Address;
    //        this.txtJobTitle.Text = runMethod.Agent_JobTitle;
    //        this.txtPhone.Text = runMethod.Agent_Phone;
    //        this.txtFax.Text = runMethod.Agent_Fax;
    //        this.txtPhone2.Text = runMethod.Agent_Phone2;
    //        this.txtContactPerson2.Text = runMethod.Agent_MobilePhone;
    //        this.txtFax2.Text = runMethod.Agent_MobilePhone2;
    //        this.txtWebSite.Text = runMethod.Agent_WebSite;
    //        this.txtEmailAddress.Text = runMethod.Agent_EmailAddress;
    //        this.txtEmailAddress2.Text = runMethod.Agent_EmailAddress2;
    //        this.txtContactPerson2.Text = runMethod.Agent_ContactPerson2;
    //        this.txtFax2.Text = runMethod.Agent_Fax2;
    //    }
    //    catch (NullReferenceException)
    //    {
    //    }
    //    this.setButtons(string.Empty);
    //}

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "Agents");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowed.aspx");
        }
        else
        {
            if (!this.chkForOperation.Checked)
            {
                this.setButtons(string.Empty);
                this.setTextReadOnly(false);
            }
            if (!this.Page.IsPostBack)
            {
               // this.chkForOperation.Checked = true;
                this.cbForUpdate.Checked = true;
                btnDelete.Enabled = true;
                Agent runMethod = new Agent(Request["Agent"].ToString());
                runMethod.GetAgentDetails();
                this.txtAgent.Text = runMethod.Agent_Code;
                this.txtName.Text = runMethod.Agent_Name;
                this.txtChiName.Text = runMethod.Agent_ChineseName;
                this.txtContactPerson.Text = runMethod.Agent_ContactPerson;
                this.txtAddress.Text = runMethod.Agent_Address;
                this.txtJobTitle.Text = runMethod.Agent_JobTitle;
                this.txtPhone.Text = runMethod.Agent_Phone;
                this.txtFax.Text = runMethod.Agent_Fax;
                this.txtPhone2.Text = runMethod.Agent_Phone2;
                this.txtContactPerson2.Text = runMethod.Agent_MobilePhone;
                this.txtFax2.Text = runMethod.Agent_MobilePhone2;
                this.txtWebSite.Text = runMethod.Agent_WebSite;
                this.txtEmailAddress.Text = runMethod.Agent_EmailAddress;
                this.txtEmailAddress2.Text = runMethod.Agent_EmailAddress2;
                this.txtContactPerson2.Text = runMethod.Agent_ContactPerson2;
                this.txtFax2.Text = runMethod.Agent_Fax2;
                ((Label)this.Master.FindControl("lblMstTitle")).Text = " | " + ISitemap.Settings + " | " + ISitemap.MaintenanceFiles.ToString() + " | " + ISitemap.AgentsUpdate;
                this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");

                ViewState["isRestore"] = false;

                if (runMethod.IsDelete)
                {
                    if (Session["SuperUser"] != null)
                    {
                        if (Convert.ToBoolean(Session["SuperUser"]))
                        {
                            ViewState["isRestore"] = true;
                        }
                    }
                }

                bool isRestore = Convert.ToBoolean(ViewState["isRestore"]);

                if (isRestore)
                {
                    this.setButtons("restore");
                    return;
                }
                else
                {
                    setButtons(string.Empty);
                }

            }
        }
    }

    //protected void Search()
    //{
    //    AgentsFacade facade = new AgentsFacade();
    //    SqlParameter[] sqlparam = new SqlParameter[4];
    //    sqlparam[0] = new SqlParameter();
    //    sqlparam[0].ParameterName = "@Agent";
    //    sqlparam[0].Value = this.txtSearchAgent.Text.ToString();
    //    sqlparam[1] = new SqlParameter();
    //    sqlparam[1].ParameterName = "@Name";
    //    sqlparam[1].Value = this.txtSearchName.Text.ToString();
    //    sqlparam[2] = new SqlParameter();
    //    sqlparam[2].ParameterName = "@ChineseName";
    //    sqlparam[2].Value = this.txtSearchChineseName.Text.ToString();
    //    sqlparam[3] = new SqlParameter();
    //    sqlparam[3].ParameterName = "@ContactPerson";
    //    sqlparam[3].Value = this.txtSearchContactPerson.Text.ToString();
    //    DbParameter[] param = sqlparam;
    //    DataView dv = facade.GetsAgents("_IPMS_AgentSearch_SP", param).DefaultView;
    //    this.GridView1.DataSourceID = string.Empty;
    //    this.GridView1.DataSource = dv;
    //    this.GridView1.DataBind();
    //}

    protected void setButtons(string action)
    {
        //switch (action)
        //{
        //    case "new":
        //        this.btnNew.Enabled = false;
        //        this.btnModify.Enabled = false;
        //        this.btnSave.Enabled = true;
        //        this.btnDelete.Enabled = false;
        //        this.chkForOperation.Checked = true;
        //        return;

        //    case "modify":
        //        this.btnNew.Enabled = false;
        //        this.btnModify.Enabled = false;
        //        this.btnSave.Enabled = true;
        //        this.btnDelete.Enabled = false;
        //        this.chkForOperation.Checked = true;
        //        return;

        //    case "save":
        //        this.btnNew.Enabled = true;
        //        this.btnModify.Enabled = false;
        //        this.btnSave.Enabled = false;
        //        this.btnDelete.Enabled = false;
        //        return;
        //}

        switch (action)
        {
            case "restore":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = false;
                this.btnDelete.Visible = false;
                this.btnRestore.Visible = true;
                return;
        }

        this.btnNew.Enabled = true;
        this.btnModify.Enabled = this.txtAgent.Text.Length != 0;
        this.btnSave.Enabled = true;
        this.btnDelete.Enabled = this.txtAgent.Text.Length != 0;
        this.btnRestore.Visible = false;
    }

    protected void btnRestore_Click(object sender, EventArgs e)
    {
        Agent agent = new Agent(this.txtAgent.Text.Trim());

        string updateBy = this.Page.User.Identity.Name.ToString();
        string updateIP = HttpContext.Current.Request.UserHostAddress;

        bool isSuccess = agent.Update(false, updateBy, updateIP, this.txtAgent.Text.Trim());

        string trueUpdateStr = string.Empty;
        string falseUpdateStr = string.Empty;
        if (Session["Culture"] != null)
        {

            if (Session["Culture"].ToString() == "zh-TW")
            {
                trueUpdateStr = "恢復成功!";
                falseUpdateStr = "恢復失敗!";

            }
            else if (Session["Culture"].ToString() == "zh-CN")
            {
                trueUpdateStr = "恢复成功!";
                falseUpdateStr = "恢复失败!";

            }
            else
            {
                trueUpdateStr = "Restore succeed!";
                falseUpdateStr = "Restore failed!";

            }
        }

        if (isSuccess)
        {
            IPMS.Common.Jscript.AlertAndRedirect(trueUpdateStr, "OptAgents.aspx", this.Page);
        }
        else
        {
            IPMS.Common.Jscript.Alert(falseUpdateStr, this.Page);
        }
    }

    protected void setTextReadOnly(bool bBool)
    {
       // this.txtAgent.ReadOnly = bBool;
        this.txtName.ReadOnly = bBool;
        this.txtChiName.ReadOnly = bBool;
        this.txtContactPerson.ReadOnly = bBool;
        this.txtAddress.ReadOnly = bBool;
        this.txtJobTitle.ReadOnly = bBool;
        this.txtPhone.ReadOnly = bBool;
        this.txtFax.ReadOnly = bBool;
        this.txtPhone2.ReadOnly = bBool;
        this.txtContactPerson2.ReadOnly = bBool;
        this.txtFax2.ReadOnly = bBool;
        this.txtWebSite.ReadOnly = bBool;
        this.txtEmailAddress.ReadOnly = bBool;
        this.txtEmailAddress2.ReadOnly = bBool;
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("OptAgents.aspx");
    }
}
